


#include <getopt.h>
#include "zlib.h"
#include "qelib.h"



void zlib_file_compress(const char *input_file, const char *output_file) 
{    
    int len;
    char buf[16384];
    FILE *fp = fopen(input_file, "rb");
    gzFile out = gzopen(output_file, "wb6f");

    while(1) {
        len = fread(buf, 1, 16384, fp);
        if (len == 0)
            break;
        if (gzwrite(out , buf, (unsigned)len)  !=  len) {
            qe_error("write error");
        }
    }

    fclose(fp);
    gzclose(out);
}

void zlib_file_decompress(const char *input_file, const char *output_file) 
{
    int len;
    char buf[16384];
    FILE *fp = fopen(output_file, "wb");
    gzFile in = gzopen(input_file, "rb");
    while (1) {
        len  =  gzread(in, buf, sizeof(buf));
        if (len <= 0) {
            break;
        }
        fwrite(buf, len, 1, fp);
    }
    fclose(fp);
    gzclose(in);    
}

static void usage(void)
{
    printf("\n");
    printf("lz4-test <cmd> <opt>\n");
    printf("  -h,?,--help          print help information\n");
    printf("  -i,--input           input file\n");
    printf("  -o,--output          output file\n");
    printf("  -d,--decompare       decompare mode\n");
    printf("\n");
}

int main(int argc, char *argv[])
{
    int opt;
    int decompare = 0;
    char *input_file  = QE_NULL;
    char *output_file = QE_NULL;

    static const struct option long_opts[] = {
        {"help",      no_argument,       NULL,  'h'},
        {"input",	  required_argument, NULL,  'i'},
        {"output",    required_argument, NULL,  'o'},
        {"decompare", no_argument,       NULL,  'd'},
        {NULL, 0, NULL, 0}
    };

    qelog_init(QELOG_DEBUG, QELOG_HMS|QELOG_LV|QELOG_CL);

    while ((opt = getopt_long(argc, argv, "i:o:d?h-", long_opts, NULL)) != -1) {
        
        switch (opt) {
        
        case 'i':
            input_file = optarg;
            break;

        case 'o':
            output_file = optarg;
            break;

        case 'd':
            decompare = 1;
            break;

        case '?':
        case 'h':
        default:
            usage();
            exit(EXIT_SUCCESS);
        }
    }

    if (!input_file || !output_file) {
        qe_error("invalid param");
        return 0;
    }

    if (decompare) {
        qe_info("decpmpare %s->%s", input_file, output_file);
        zlib_file_decompress(input_file, output_file);
    } else {
        qe_info("cpmpare %s->%s", input_file, output_file);
        zlib_file_compress(input_file, output_file);
    }

    return 0;
}